package com.itheima.service.system.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.system.UserMapper;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.SystemSet;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.utils.MD5Util;
import com.itheima.utils.MysqlUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import static com.itheima.utils.SmsDemo.sendSms;

public class UserServiceImpl implements UserService {
    // 2021/10/15 start by guowenliang
    // 登录查找用户
    @Override
    public boolean findUser(User user) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = new ArrayList<>();
        // 对密码进行加密
        try {
            user.setPassword((MD5Util.md5(user.getPassword())));
            userList = usermapper.findUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        // 找到返回true，没找到返回false
        if (userList.size() == 0) {
            return false;
        } else {
            return true;
        }
    }

    // 注册用户
    @Override
    public void register(User user) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
        // 生成userId,对密码进行加密
        user.setUserId(UUID.randomUUID().toString());
        user.setPassword((MD5Util.md5(user.getPassword())));
        usermapper.register(user);
        sqlSession.close();
    }
    // 2021/10/15 end by guowenliang

    @Override
    public void save(User user) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.addUser(user);
        sqlSession.close();
    }

    @Override
    public void delete(String id) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.delete(id);
        sqlSession.close();
    }

    @Override
    public void updateUser(User user) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(user);
        sqlSession.close();
    }

    @Override
    public User findById(String id) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findById(id);
        sqlSession.close();
        return user;
    }

    @Override
    public List<User> findAll() {
        //获取sqlSession
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        return userMapper.findAll();
    }

    @Override
    public PageInfo findByPage(String pageNum, String pageSize ) {
        // 查询所有用户，分页查询
        int num = pageNum == null || pageNum == "" ? 1 : Integer.parseInt(pageNum);
        int size = pageSize == null || pageSize == "" ? 5 : Integer.parseInt(pageSize);
        PageHelper.startPage(num, size);
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.findAll();
        PageInfo pageInfo = new PageInfo(userList);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public PageInfo findUserByCondition(String pageNum,String pageSize,String searchUserName, String searchEmail, String searchDept, String searchState, String searchGender) {
        int num = pageNum == null || pageNum == "" ? 1 : Integer.parseInt(pageNum);
        int size = pageSize == null || pageSize == "" ? 5 : Integer.parseInt(pageSize);
        PageHelper.startPage(num, size);
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.findUserByCondition(searchUserName,searchEmail,searchDept,searchState,searchGender);
        PageInfo pageInfo = new PageInfo(userList);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public String getCode(String phone) {
        // 生成随机数
        String code = getRandomString(6);
        System.out.println(code);
        try {
            // 发送短信验证码
            SendSmsResponse response = sendSms(phone,code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    // 随机产生a-zA-Z0-9的字符串，长度为length
    public static String getRandomString(int length) {
        //产生随机数
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        //循环length次
        for (int i = 0; i < length; i++) {
            //产生0-2个随机数，既与a-z，A-Z，0-9三种可能
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                //如果number产生的是数字0；
                case 0:
                    //产生A-Z的ASCII码
                    result = Math.round(Math.random() * 25 + 65);
                    //将ASCII码转换成字符
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    //产生a-z的ASCII码
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    //产生0-9的数字
                    sb.append(String.valueOf
                            (new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }


    @Override
    public List<User> findUserAndRole(String userId) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.findUserAndRole(userId);
        sqlSession.close();
        return userList;
    }

    // 查询用户和对应角色
    @Override
    public List<Role> userRoleList(String userId) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<Role> roleList = userMapper.userRoleList(userId);
        sqlSession.close();
        return roleList;
    }

    @Override
    public void updateRole(String[] roleIds, String userId) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 先删除user所有的角色
        userMapper.deleteRole(userId);
        for (String roleId : roleIds) {
            // 挨个添加角色
            userMapper.addRole(userId,roleId);
        }
        sqlSession.close();
    }

    @Override
    public User findUserByUsername(String userName) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findUserByUsername(userName);
        return user;
    }

    @Override
    public void UploadPicture(User user) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
         userMapper.UploadPicture(user);
    }

    @Override
    public User findUserAndPassword(String username, String password) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.findUserAndPassword(username, password);
        sqlSession.close();
        return user;
    }

    @Override
    public void updatePassword(String username, String password) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(password);
        String passwordL= MD5Util.md5(password);
        System.out.println(passwordL);
        mapper.updatePassword(username, passwordL);
    }


    @Override
    public List<SystemSet> findSystemSet() {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<SystemSet> systemSetList = mapper.findSystemSet();
        sqlSession.close();
        return systemSetList;
    }

    @Override
    public void updatePageSize(String moduleName, String moduleNamePageSize) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updatePageSize(moduleName,moduleNamePageSize);
        sqlSession.close();
    }

    @Override
    public SystemSet findSystemSetByModuleName(String moduleName) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        SystemSet systemSet = userMapper.findSystemSetByModuleName(moduleName);
        sqlSession.close();
        return systemSet;
    }

    @Override
    public User findUserByNameAndEmail(String username, String email) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        System.out.println(username);
        System.out.println(email);
        User user = mapper.findUserByNameAndEmail(username, email);


        return user;
    }

    @Override
    public void updatePasswordByNameAndEmail(String username, String email, String password) {
        SqlSession sqlSession = MysqlUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        String pw=MD5Util.md5(password);
        mapper.updatePasswordByNameAndEmail(username, email, pw);

    }


}
